<template>
  <div class="login-account">
    <el-form
      status-icon
      label-width="65px"
      :rules="rules"
      :model="account"
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input autocomplete="off" v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          autocomplete="off"
          v-model="account.password"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item label="验证码" prop="code">
        <div class="get-code">
          <el-input v-model="account.code"></el-input>
          <!-- <el-button type="primary" class="getcode-btn">获取验证码</el-button> -->
          <img :src="captUrl" class="getcode-btn" @click="handleCode" />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { ElForm } from 'element-plus'
import { useStore } from 'vuex'

import { rules } from '../config/account-config'
import localCache from '@/utils/cache'
import lzRequest from '@/service'

export default defineComponent({
  setup() {
    onMounted(() => {
      handleCode()
    })

    const captUrl = ref()
    const store = useStore()
    const account = reactive({
      name: localCache.getCache('name') ?? '',
      password: localCache.getCache('passwd') ?? '',
      captId: '',
      code: ''
    })

    const formRef = ref<InstanceType<typeof ElForm>>()

    const loginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          // console.log('执行真正登陆')
          // 1. 判断是否需要记住密码
          if (isKeepPassword) {
            // 本地缓存
            localCache.setCache('name', account.name)
            localCache.setCache('passwd', account.password)
          } else {
            localCache.deleteCache('name')
            localCache.deleteCache('passwd')
          }
          // 2. 执行真正的登陆逻辑
          store.dispatch('login/accountLoginAction', { ...account })
        }
      })
    }

    interface IResDate {
      code: number
      data: any
    }

    // 请求验证码
    const handleCode = () => {
      lzRequest
        .get<IResDate>({
          url: '/captcha'
        })
        .then((res) => {
          // console.log(res.data)
          const { captchaId, coderurl } = res.data
          account.captId = captchaId
          captUrl.value = coderurl
          // console.log(captUrl.value)
          // console.log(coderurl)
        })
    }

    return {
      account,
      rules,
      formRef,
      captUrl,
      loginAction,
      handleCode
    }
  }
})
</script>

<style scoped>
.get-code {
  display: flex;
}
.getcode-btn {
  margin-left: 8px;
  display: inline-block;
  width: 120px;
  height: 40px;
}
</style>
